<template>
  <div v-loading="loading" class="app-container">
    <div class="filter-container">
      <el-button v-if="isFinishButtonVisible" class="filter-item" type="primary" icon="el-icon-check" @click="finishWorkcard">完成工卡</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-refresh" @click="refreshWorkcard">刷新</el-button>
    </div>
    <el-card class="box-card">
      <div class="demo-input-suffix">
        <h3>工卡ID: {{ ID }}</h3>
        <h3>
          <span>工艺规范:</span>
          <el-button v-if="workcard&&workcard.gygf&&workcard.gygf.uid" type="text" @click="displayAttachment(ID, workcard.gygf.path)">
            {{ workcard.gygf.name||'' }}
          </el-button>
          <el-button v-else type="text" disabled>无附件</el-button>
        </h3>
        <el-card v-if="!!editableAttrs&&editableAttrs.length!==0" class="box-card" style="margin-bottom: 20px;">
          <el-form label-width="80px">
            <el-form-item v-for="attr in editableAttrs" :key="attr.name" :label="attr.name">
              <el-input v-model="attr.value" :readonly="!isWorkCardAttrEditable" type="number" @blur="saveAttr(attr)">
                <template v-if="attr.name.indexOf('温度')!==-1" slot="append">摄氏度</template>
                <template v-if="attr.name==='大气压力'" slot="append">Mpa</template>
                <template v-if="attr.name==='湿度'" slot="append">%RH</template>
              </el-input>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
      <div class="filter-container">
        <el-select
          v-model="selectedRole"
          placeholder="请选择角色"
          clearable
          style="width: 190px"
          class="filter-item"
        >
          <el-option v-for="role in roles" :key="role" :label="role" :value="role"/>
        </el-select>
      </div>
      <work-unit :workdata="workinstructions" :role="selectedRole" :workuid="workcard.workuid" :editable="editable" :id="ID"/>
    </el-card>
  </div>
</template>

<script>
import { getWorkcard, saveWorkcard } from '@/utils/storage'
import WorkUnit from '@/components/WorkUnit'
import { showFile, deletePhoto, saveAttachment, savePhoto } from '@/utils/file'
import { requestAttachment, requestWorklist } from '@/api/workcard'
import { mergeExistWorkcard, getWorkcardID } from '@/utils/workcard-util'
import { getUsername } from '@/utils/auth'

export default {
  components: { WorkUnit },
  props: {
    workuid: {
      type: String,
      default: '',
      required: true
    }
  },
  data() {
    return {
      workcard: {},
      workinstructions: [],
      temperature: 35,
      pressure: 1025,
      humidity: 55,
      roles: [],
      selectedRole: '',
      editable: true,
      editableAttrs: [],
      isFinishButtonVisible: false,
      ID: '',
      loading: false
    }
  },
  computed: {
    isWorkCardAttrEditable: function() {
      const that = this
      if (!that.editable) {
        return false
      }
      if (!that.workcard) {
        return false
      } else if (that.workcard.executors.filter(v => v.name.indexOf(getUsername()) !== -1 && v.role === '工作者').length === 0) {
        return false
      }

      return true
    }
  },
  watch: {
    workcard: {
      handler: function(newValue, oldValue) {
        const that = this
        if (newValue.isfinished === 'True') {
          that.editable = false
        } else {
          that.editable = true
        }
        that.workinstructions = newValue.workinstructions
        that.ID = getWorkcardID(newValue)
      },
      deep: true
    }
  },
  mounted: function() {
    const that = this
    getWorkcard(this.workuid).then(
      workcard => {
        if (workcard && 'workcard' in workcard) {
          that.workcard = workcard.workcard
          that.roles = that.workcard.executors.map(v => v.role).filter((obj, index, self) =>
            index === self.findIndex((e) => (e === obj)))
          that.selectedRole = that.defaultSelectedRole()
          that.editableAttrs = that.workcard.workrelattrs.filter(v => v.editable === true)
          that.isFinishButtonVisible = that.displayFinishButton()
        }
      }
    )
  },
  methods: {
    defaultSelectedRole() {
      if (this.workcard.workType === '测试系统检查' || this.workcard.workType === '测试校准') {
        return '复检'
      } else {
        return '工作者'
      }
    },
    isEditableAttrEditable() {

    },
    displayAttachment(id, path) {
      showFile(id, path)
    },
    displayFinishButton() {
      const username = getUsername()
      let find = false
      if (this.workcard.worktype === '测试系统检查' || this.workcard.worktype === '测试校准') {
        find = this.workcard.executors
          .findIndex(executor => executor.name.indexOf(username) !== -1 && executor.role === '复检')
      } else {
        find = this.workcard.executors
          .findIndex(executor => executor.name.indexOf(username) !== -1 && executor.role === '检验')
      }
      if (find !== -1) {
        return true
      } else {
        return false
      }
    },
    saveAttr(attr) {
      const _attr = this.workcard.workrelattrs.find(v => v.name === attr.name)
      if (_attr && JSON.stringify(attr) !== '{}') {
        _attr.value = attr.value
        saveWorkcard(this.workcard)
      }
    },
    finishWorkcard() {
      const that = this
      this.$confirm('工卡完成后将不可编辑, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        getWorkcard(this.workuid).then(
          workcard => {
            workcard.workcard.isfinished = 'True'
            saveWorkcard(workcard.workcard).then(
              () => {
                that.workcard = workcard.workcard
                that.$message({
                  type: 'success',
                  message: '工卡已完成!'
                })
              }
            )
          }
        )
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消完成操作'
        })
      })
    },
    refreshWorkcard() {
      if (!this.$store.state.app.online) {
        this.$message.error('离线状态下不能同步服务器工卡！')
        return
      }
      const that = this
      this.$confirm('刷新操作会将服务器工卡覆盖您的当前工卡，所有输入都将被覆盖, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        that.downloadWorkcard()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消刷新操作！'
        })
        that.loading = false
      })
    },
    downloadWorkcard() {
      const that = this
      let count = 0
      let error = {}
      // 下载
      this.loading = true
      count++
      console.log('[workinstruction]-[refresh]-begin-count:' + count)
      return requestWorklist().then(
        response => {
          const all = response.data
          all.forEach(
            workcard => {
              if (workcard.workuid === that.workuid) {
                if ('isfinished' in workcard === false && 'isFinished' in workcard === false) {
                  workcard.isfinished = 'False'
                }

                if ('isFinished' in workcard) {
                  workcard.isfinished = workcard.isFinished || 'False'
                  delete workcard.isFinished
                }

                if ('isfinished' in workcard && !workcard.isfinished) {
                  workcard.isfinished = 'False'
                }

                mergeExistWorkcard(workcard).then(
                  arrObj => {
                    const mergedWorkcard = arrObj[0]
                    const newPhotoObjects = arrObj[1]
                    const deletePhotoObjects = arrObj[2]
                    const attachementObjects = arrObj[3]

                    saveWorkcard(mergedWorkcard)

                    deletePhotoObjects.forEach(photoObject => {
                      deletePhoto(that.ID, photoObject.path)
                    })

                    newPhotoObjects.forEach(
                      photoObject => {
                        if (photoObject.uid) {
                          count++
                          console.log('[workinstruction]-[refresh]-download photo-begin-count:' + count)
                          requestAttachment(photoObject.uid).then(
                            blob => {
                              console.log('[download]-[refresh]-download photo: ' + photoObject.path + ', size: ' + blob.size)
                              savePhoto(that.ID, photoObject.path, blob)
                            }
                          ).catch(
                            err => {
                              console.log('[download]-[refresh]-download photo err: ')
                              console.log(err)
                              error = err
                            }
                          ).finally(
                            () => {
                              count--
                              console.log('[workinstruction]-[refresh]-download photo-finally-count:' + count)
                              if (count === 0) {
                                that.loading = false
                                if (JSON.stringify(error) !== '{}') {
                                  if (error.message === 'Network Error' || error.message === 'Failed to fetch') {
                                    that.$message.error('网络错误，未连接到服务器！')
                                  } else {
                                    that.$message.error(error)
                                  }
                                } else {
                                  that.workcard = mergedWorkcard
                                  that.$message.success('工卡刷新成功！')
                                }
                              }
                            }
                          )
                        }
                      }
                    )

                    attachementObjects.forEach(
                      attachment => {
                        if (attachment.uid) {
                          count++
                          console.log('[workinstruction]-[refresh]-download attachment-begin-count:' + count)
                          requestAttachment(attachment.uid).then(
                            blob => {
                              console.log('[download]-[refresh]-download attachment: ' + attachment.path + ', size: ' + blob.size)
                              saveAttachment(that.ID, attachment.path, blob)
                            }
                          ).catch(
                            err => {
                              console.log('[download]-[refresh]-download attachment err: ')
                              console.log(err)
                              error = err
                            }
                          ).finally(
                            () => {
                              count--
                              console.log('[workinstruction]-[refresh]-download attachment-finally-count:' + count)
                              if (count === 0) {
                                that.loading = false
                                if (JSON.stringify(error) !== '{}') {
                                  if (error.message === 'Network Error' || error.message === 'Failed to fetch') {
                                    that.$message.error('网络错误，未连接到服务器！')
                                  } else {
                                    that.$message.error(error)
                                  }
                                } else {
                                  that.workcard = mergedWorkcard
                                  that.$message.success('工卡刷新成功！')
                                }
                              }
                            }
                          )
                        }
                      }
                    )
                  }
                )
              }
            }
          )
        }
      ).catch(
        err => {
          error = err
        }
      ).finally(
        () => {
          count--
          console.log('[workinstruction]-[refresh]-finally-count:' + count)
          if (count === 0) {
            that.loading = false
            if (JSON.stringify(error) !== '{}') {
              if (error.message === 'Network Error' || error.message === 'Failed to fetch') {
                that.$message.error('网络错误，未连接到服务器！')
              } else {
                that.$message.error(error)
              }
            }
          }
        }
      )
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.panel-group {
  margin-top: 18px;
  .card-panel-col {
    margin-bottom: 32px;
  }
  .card-panel {
    height: 108px;
    font-size: 12px;
    position: relative;
    overflow: hidden;
    color: #666;
    background: #fff;
    box-shadow: 4px 4px 40px rgba(0, 0, 0, 0.05);
    border-color: rgba(0, 0, 0, 0.05);
    .card-panel-icon-wrapper {
      float: left;
      margin: 26px 0 0 0px;
      padding: 8px;
      // transition: all 0.38s ease-out;
      border-radius: 6px;
    }
    .card-panel-icon {
      float: left;
      // font-size: 48px;
      font-size: 35px;
    }
    .card-panel-description {
      float: right;
      font-weight: bold;
      // margin: 26px;
      // margin-left: 30px;
      margin-right: 26px;
      margin-top: 26px;
      // margin-left: 1px;
      .card-panel-text {
        line-height: 18px;
        color: rgba(0, 0, 0, 0.45);
        font-size: 16px;
        margin-bottom: 12px;
      }
      .card-panel-num {
        .el-input__inner {
          font-size: 20px;
          border: none;
          color: #666;
          align-content: center;
          font-weight: bold;
          width: 60px;
          margin-left: 0;
          padding: 0px 15px 0px 0px !important;
          &:focus {
            outline: none;
            border: none;
            border-bottom: 1px solid; // fixes the height issue
            color: #666;
          }
        }
      }
    }
  }
}
</style>
